package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 韩先楚
 * 菜品服务实现类
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 新增菜品和口味信息
     * @param dishDTO
     * @return
     */
   @Transactional
    public void saveDishAndFlavor(DishDTO dishDTO) {
       Dish dish = new Dish();
       BeanUtils.copyProperties(dishDTO, dish);
       //向菜品表插入一条数据
       dishMapper.insert(dish);

       //获取菜品id
       Long dishId = dish.getId();

       //获取口味数据
        //向口味表插入多条数据
       List<DishFlavor> flavors = dishDTO.getFlavors();
       //判断是否有口味数据
       if (flavors!= null && flavors.size() > 0) {
           for (DishFlavor flavor : flavors)
               flavor.setDishId(dishId);
           dishFlavorMapper.insertFlavor(flavors);
       }
   }

    /**
     * 菜品分页查询
     * @param
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
     List<DishVO> dishVOS =  dishMapper.pageQuery(dishPageQueryDTO);
        Page<DishVO> page = (Page<DishVO>) dishVOS;
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 菜品批量删除
     * @param
     * @return
     */
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        //判断菜品是否可以删除 -- 判断菜品是否在起售中
         for (Integer id : ids) {
             Dish dish = dishMapper.deleteById(id);
             if (dish.getStatus()== StatusConstant.ENABLE)
             {
                 throw  new DeletionNotAllowedException("菜品正在起售中，不能删除") ;
             }
         }
        //判断菜品是否可以删除 -- 判断菜品是否关联套餐
        List<Integer> setMealId = setMealDishMapper.getDishIdsBySetMealId(ids);
         if (setMealId != null && setMealId.size() > 0)
         {
             //当前菜品被关联了,不能删除
             throw new DeletionNotAllowedException("菜品已关联套餐，不能删除");

         }
        //删除菜品
        dishMapper.deleteBatch(ids);

        //删除跟菜品关联的口味数据
        dishMapper.deleteFlavors(ids);

    }

    /**
     * 根据id查询菜品
     */
    public DishVO getDishById(Integer id) {
        //根据id查询菜品
        Dish dish = dishMapper.deleteById(id);
        //根据菜品id查询口味数据
        List<DishFlavor> flavors = dishFlavorMapper.getFlavorsByDishId(id);
       //封装到DishVo中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 根据id修改菜品和其关联的口味
     */
    @Transactional
    public void updateDishAndFlavor(DishDTO dishDTO) {
         //先修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断是否有口味数据
        if (flavors != null && flavors.size() > 0) {
            //先删除原有的口味数据
            dishFlavorMapper.deleteFlavorsByDishId(dishDTO.getId());
            //插入dish_id
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
            }
            //插入新的口味数据
            dishFlavorMapper.insertFlavor(flavors);
        }
    }

    /**菜品起售、停售
     *
     * @param status
     */
    public void updateStatus(Integer id, Integer status) {
        dishMapper.updateStatus(id, status);
    }

    /**
     * 根据分类id查询菜品
     * @param
     * @return
     */
    public List<Dish> listByCategoryId(Integer categoryId) {
        return dishMapper.listByCategoryId(categoryId);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) throws JsonProcessingException {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            long id = d.getId();
            int id1 = (int)id;
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getFlavorsByDishId(id1);

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
      //将查询到的菜品和口味数据加到redis中,并设置过期时间
        String json = objectMapper.writeValueAsString(dishVOList);
        redisTemplate.opsForValue().set("dish:"+dish.getCategoryId(),json,1000*60*2, TimeUnit.SECONDS);
        //返回查询到的菜品和口味数据
        return dishVOList;
    }

}
